package com.timedomain.him.remake.ui;

import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;

import com.timedomain.him.remake.R;
import com.timedomain.him.remake.core.ListPlayer;
import com.timedomain.him.remake.models.MorningCall;
import com.timedomain.him.remake.ui.common.PlayerActivity;
import com.timedomain.him.remake.utils.AppSettings;
import com.timedomain.him.remake.utils.BaseActivity;
import com.timedomain.him.remake.utils.DB;
import com.timedomain.him.remake.utils.MorningCallManager;
import com.timedomain.him.remake.utils.TimeUtils;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MorningCallActivity extends BaseActivity {

    private ListView listMorningCallMain;
    private Button btnMorningCallAll;
    private Button btnMorningCallFav;
    private TextView txtMorningCallTime;
    private TextView txtMorningCallDate;
    private void initUI(){	 listMorningCallMain = (ListView)findViewById(R.id.listMorningCallMain);
        btnMorningCallAll = (Button)findViewById(R.id.btnMorningCallAll);
        btnMorningCallFav = (Button)findViewById(R.id.btnMorningCallFav);
        txtMorningCallTime = (TextView)findViewById(R.id.txtMorningCallTime);
        txtMorningCallDate = (TextView)findViewById(R.id.txtMorningCallDate);
    }

    private void showNextTime(){
        long nextTime = MorningCallManager.getNextTime();
        if(nextTime == -1){
            txtMorningCallDate.setText("时间");
            txtMorningCallTime.setText("未定");
            return;
        }
        long dateStamp = TimeUtils.toDateStamp(nextTime);
        long todayDateStamp = TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone());
        String morningCallTime = new SimpleDateFormat("HH:mm", Locale.US).format(
            new Date(TimeUtils.toSystemTimeStamp(
                    nextTime
            ))
        );
        if(todayDateStamp == dateStamp){
            txtMorningCallDate.setText("今天");
        }
        else{
            txtMorningCallDate.setText("明天");

        }
        txtMorningCallTime.setText(morningCallTime);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_morningcall);
        initUI();
        showNextTime();
        listAdapter = new MorningCallListAdapter(this);
        listMorningCallMain.setAdapter(listAdapter);
        loadList();
    }

    public void setMorningCallTime(View view) {
        TimePickerDialog timePickerDialog = new TimePickerDialog(this,  new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                int min = 4 * 60 + 30;
                int max = 9 * 60 + 59;
                int current = hourOfDay * 60 + minute;
                if(current < min || current > max){
                    showToast("这个时间范围不合适，换一个试试吧");
                    return;
                }
                AppSettings.morningCallIsManual = false;
                AppSettings.morningCallHour = hourOfDay;
                AppSettings.morningCallMinute = minute;
                AppSettings.nightChat = false;
                AppSettings.nightChatRequiredMorningCall = false;

                boolean canTriggerToday =
                        TimeUtils.dateStampToTimeStamp(TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone()))
                        + hourOfDay * 3600L * 1000L
                        + minute * 60L * 1000L
                        > TimeUtils.getTimeStampIgnoreTimeZone() + 30000L;

                long todayDateStamp = TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone());

                if(!canTriggerToday){
                    AppSettings.morningCallDateStamp = todayDateStamp;
                }

                AppSettings.saveSettings(MorningCallActivity.this);

                MorningCallManager.setNextMorningCall(MorningCallActivity.this);
                showNextTime();
            }
        }, AppSettings.morningCallHour,AppSettings.morningCallMinute,true);
        timePickerDialog.show();
    }

    private MorningCallListAdapter listAdapter = null;
    private int offset = 0;
    private boolean showAll = true;
    private void loadList(){
        List<MorningCall> result = DB.MorningCall.Query(offset,!showAll);
        List<MorningCallObjectHolder> holders = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            MorningCallObjectHolder oh = new MorningCallObjectHolder();
            oh.object = result.get(i);
            holders.add(oh);
        }
        offset+=result.size();
        if(listAdapter.getCount() > 0){
            MorningCallObjectHolder last = listAdapter.getItem(listAdapter.getCount()-1);
            if(last.state == MorningCallObjectHolder.STATE_LOAD_MARK){
                listAdapter.remove(last);
            }
        }
        if(result.size() > 0){
            listAdapter.addAll(holders);
            MorningCallObjectHolder loadMark = new MorningCallObjectHolder();
            loadMark.state = MorningCallObjectHolder.STATE_LOAD_MARK;
            listAdapter.add(loadMark);
        }
        setTimeout(()->{listAdapter.notifyDataSetChanged();},1);
    }

    public void showAll(View view) {
        if(!showAll){
            showAll = true;
            offset = 0;
            listAdapter.clear();
            loadList();
            btnMorningCallAll.setTextColor(0xff302f2f);
            btnMorningCallFav.setTextColor(0x99302F2F);
        }
    }

    public void showFav(View view) {
        if(showAll){
            showAll = false;
            offset = 0;
            listAdapter.clear();
            loadList();

            btnMorningCallFav.setTextColor(0xff302f2f);
            btnMorningCallAll.setTextColor(0x99302F2F);
        }
    }

    private static class MorningCallObjectHolder{
        public MorningCall object;
        public int state=0;

        public static final int STATE_LOAD_MARK = 114514;

    }



    class MorningCallListAdapter extends ArrayAdapter<MorningCallObjectHolder>{

        public MorningCallListAdapter(@NotNull Context context) {
            super(context, R.layout.list_morning_call, new ArrayList<>());
        }

        @NotNull
        @Override
        public View getView(int position, @Nullable View convertView, @NotNull ViewGroup parent) {
            if(convertView == null){
                convertView = getLayoutInflater().inflate(R.layout.list_morning_call,null,false);
            }
            MorningCallObjectHolder model = getItem(position);
            TextView titleView = convertView.findViewById(R.id.txtMorningCallTitle);
            TextView subtitleView = convertView.findViewById(R.id.txtMorningCallSubtitle);
            ToggleButton chkFav = convertView.findViewById(R.id.chkMorningCallListFav);
            ImageButton btnPlay = convertView.findViewById(R.id.btnMorningCallListPlay);
            if(model.state == MorningCallObjectHolder.STATE_LOAD_MARK){
                setTimeout(MorningCallActivity.this::loadList,333);
                loadList();
                chkFav.setVisibility(View.GONE);
                btnPlay.setVisibility(View.GONE);
                titleView.setText("");
                subtitleView.setText("");
                return convertView;
            }
            chkFav.setVisibility(View.VISIBLE);
            btnPlay.setVisibility(View.VISIBLE);
            titleView.setText(model.object.title);
            subtitleView.setText(model.object.time+" | "+model.object.duration);
            chkFav.setOnCheckedChangeListener(null);
            chkFav.setTag(model.object);
            chkFav.setChecked(model.object.fav);
            chkFav.setOnCheckedChangeListener(MorningCallActivity.this::toggleFav);
            btnPlay.setTag(model.object);
            btnPlay.setOnClickListener(MorningCallActivity.this::playOne);
            return convertView;
        }
    }

    void toggleFav(CompoundButton view,boolean isChecked){
        MorningCall item = (MorningCall) view.getTag();
        item.fav = isChecked;
        DB.MorningCall.setFav(item.id,isChecked);
    }

    void playOne(View v){
        MorningCall call = (MorningCall) v.getTag();

        ListPlayer.PlayEntry current = new ListPlayer.PlayEntry(call.path);
        List<ListPlayer.PlayEntry> playlist = new ArrayList<>();
        for (int i = 0;i<listAdapter.getCount();i++){
            MorningCallObjectHolder holder= listAdapter.getItem(i);
            if(holder != null &&  holder.object != null){
                playlist.add(new ListPlayer.PlayEntry(holder.object.path));
            }
        }
        PlayerActivity.StartPlayer(this,playlist,current);
    }

}
